<?php
	session_start();
	
	// Clear all previous messages.
	if($_SESSION['log-err']) session_unregister('log-err');
	if($_SESSION['log-info']) session_unregister('log-info');
	
	$teacher_nic = $_POST['teacher_nic'];
	$teacher_password = $_POST['teacher_password'];
		
	// Check for completion of mandatory fields.
	if($teacher_nic == "" || $teacher_password == ""){
		$_SESSION['page'] = "visitor.php";
		$_SESSION['log-err'] = "Invalid user name or password.";
		header('Location: ../');
	}
	
	include('./dbconnection.php');
	$query_check = "SELECT * FROM teachers WHERE teacher_nic = '$teacher_nic'";
	if($user_exist = mysql_query($query_check)){
		// Check whether user exist.
		if(mysql_num_rows($user_exist)> 0){
			$row = mysql_fetch_row($user_exist);
			$name = $row[1];
			$pw = $row[2];
			// Check for accuracy of the password.
			$teacher_password = SHA1("$teacher_password");
			if($teacher_password != $pw){
				// Wrong password.
				$_SESSION['page'] = "visitor.php";
				$_SESSION['log-err'] = "Invalid user name or password.";
				header('Location: ../');
			}else{
				// User authentication successful.
				$_SESSION['page'] = "home.php";
				$_SESSION['user'] = $name;
				header('Location: ../');	
			}			
		}else{
			// Invalid user name.
			$_SESSION['page'] = "visitor.php";
			$_SESSION['log-err'] = "Invalid user name or password.";
			header('Location: ../');	
		}			
	}else{
		// SQL error occurred during the transaction.
		$_SESSION['page'] = "visitor.php";
		$_SESSION['log-err'] = "Error occured. Please try again.";
		header('Location: ../');
	}
?>